import * as fabricModule from 'fabric';
const fabric = fabricModule.fabric || fabricModule;
import EventEmitter from 'events';

/**
 * 核心编辑器类，管理Fabric.js画布和插件
 */
class EditorCore extends EventEmitter {
    constructor() {
        super();
        this.canvas = null;
        this.plugins = new Map();
        this.history = {
            stack: [],
            position: -1,
            maxSteps: 30
        };
        this.settings = {
            width: 800,
            height: 600,
            backgroundColor: '#ffffff',
            gridEnabled: false,
            rulerEnabled: false,
            snapToGrid: false,
            gridSize: 20
        };
        this.state = {
            isDrawing: false,
            selectedObject: null,
            zoom: 1,
            isDragging: false
        };
    }

    /**
     * 初始化编辑器
     */
    init(canvasEl, options = {}) {
        // 合并默认选项
        const defaultOptions = {
            fireRightClick: true,
            stopContextMenu: true,
            preserveObjectStacking: true,
            controlsAboveOverlay: true,
            selection: true,
            defaultCursor: 'default'
        };

        this.canvas = new fabric.Canvas(canvasEl, { ...defaultOptions, ...options });

        // 应用设置
        this.applySettings();

        // 设置事件监听
        this._setupEventListeners();

        // 初始化插件
        this._initializePlugins();

        // 记录初始状态
        this._recordHistory();

        return this;
    }

    /**
     * 应用编辑器设置
     */
    applySettings() {
        if (!this.canvas) return;

        this.canvas.setWidth(this.settings.width);
        this.canvas.setHeight(this.settings.height);
        this.canvas.setBackgroundColor(
            this.settings.backgroundColor,
            this.canvas.renderAll.bind(this.canvas)
        );

        if (this.settings.gridEnabled) {
            this._createGrid();
        }

        if (this.settings.rulerEnabled) {
            this._createRuler();
        }
    }

    /**
     * 注册插件
     */
    registerPlugin(name, plugin) {
        if (this.plugins.has(name)) {
            console.warn(`Plugin ${name} already exists. Overwriting...`);
        }
        this.plugins.set(name, plugin);

        // 如果画布已初始化，立即初始化插件
        if (this.canvas) {
            plugin.init(this);
        }
    }

    /**
     * 获取插件实例
     */
    getPlugin(name) {
        return this.plugins.get(name);
    }

    /**
     * 历史记录管理
     */
    _recordHistory() {
        if (!this.canvas) return;

        const json = this.canvas.toJSON();

        // 如果在历史记录中间位置进行了新操作，清除之后的记录
        if (this.history.position < this.history.stack.length - 1) {
            this.history.stack = this.history.stack.slice(0, this.history.position + 1);
        }

        this.history.stack.push(json);

        // 维护历史记录大小
        if (this.history.stack.length > this.history.maxSteps) {
            this.history.stack.shift();
        } else {
            this.history.position++;
        }

        this.emit('history:recorded', this.history.position);
    }

    /**
     * 撤销操作
     */
    undo() {
        if (this.history.position > 0) {
            this.history.position--;
            this._restoreHistory();
        }
    }

    /**
     * 重做操作
     */
    redo() {
        if (this.history.position < this.history.stack.length - 1) {
            this.history.position++;
            this._restoreHistory();
        }
    }

    /**
     * 还原历史状态
     */
    _restoreHistory() {
        if (!this.canvas) return;

        const state = this.history.stack[this.history.position];
        this.canvas.loadFromJSON(state, () => {
            this.canvas.renderAll();
            this.emit('history:restored', this.history.position);
        });
    }

    /**
     * 设置事件监听
     */
    _setupEventListeners() {
        if (!this.canvas) return;

        // 对象选择事件
        this.canvas.on('selection:created', (e) => {
            this.state.selectedObject = e.target;
            this.emit('object:selected', e.target);
        });

        this.canvas.on('selection:cleared', () => {
            this.state.selectedObject = null;
            this.emit('selection:cleared');
        });

        // 对象修改事件
        this.canvas.on('object:modified', () => {
            this._recordHistory();
            this.emit('object:modified');
        });

        // 画布缩放事件
        this.canvas.on('mouse:wheel', (e) => {
            const delta = e.e.deltaY;
            let zoom = this.canvas.getZoom();
            zoom *= 0.999 ** delta;
            if (zoom > 20) zoom = 20;
            if (zoom < 0.01) zoom = 0.01;

            const point = {
                x: e.e.offsetX,
                y: e.e.offsetY
            };

            this.canvas.zoomToPoint(point, zoom);
            this.state.zoom = zoom;

            e.e.preventDefault();
            e.e.stopPropagation();
        });
    }

    /**
     * 初始化已注册的插件
     */
    _initializePlugins() {
        for (const plugin of this.plugins.values()) {
            plugin.init(this);
        }
    }

    /**
     * 创建网格
     */
    _createGrid() {
        // 实现网格绘制逻辑
    }

    /**
     * 创建标尺
     */
    _createRuler() {
        // 实现标尺绘制逻辑
    }

    /**
     * 销毁编辑器实例
     */
    destroy() {
        if (this.canvas) {
            // 清理插件
            for (const plugin of this.plugins.values()) {
                if (typeof plugin.destroy === 'function') {
                    plugin.destroy();
                }
            }

            // 清理画布
            this.canvas.dispose();
            this.canvas = null;

            // 清理事件
            this.removeAllListeners();

            // 重置状态
            this.history = {
                stack: [],
                position: -1,
                maxSteps: this.history.maxSteps
            };
            this.state = {
                isDrawing: false,
                selectedObject: null,
                zoom: 1,
                isDragging: false
            };
        }
    }
}

export default EditorCore;